//
//  XS_KCDetailVC.swift
//  XueDao
//
//  Created by 韩云智 on 2021/1/10.
//

import UIKit
import RxCocoa
import RxSwift
import RxDataSources
import SnapKit

class XS_KCplayVideohourListM: XS_BaseModel {
    var id = 0 // 课时编号
    var curriculumHourTitle = "" // 课时标题
    var duration = "" // 课时时长
    var isWatch = "" // 是否可以试看 yes/no
    var isCurrent = "" // 是否当前播放视频 yes/no
    var imgUrl = "" // 课时封面图
}
class XS_KCplayVideohourInfoM: XS_BaseModel {
    var curriculumHourTitle = "" // 课时标题
    var curriculumId = "" // 课程编号
    var duration = "" // 课时时长
    var label = "" // 课程标签
    var imgUrl = "" // 课时封面图
    var descriptionImgUrl = "" // 课时封面图
}
class XS_KCplayVideostsM: XS_BaseModel {
    var vid = "" // 视频ID
    var akScret = "" // accessKeySecret
    var regionId = "" // regionId
    var akId = "" // accessKeyId
    var stk = "" // SecurityToken
    var source = "" // 来源("backendUpload"是后台上传，"cloudLearn"是云学习）
}
class XS_KCplayVideoM: XS_BaseModel {
    var isBuy = ""
    var sts = XS_KCplayVideostsM() // sts信息
    var hourInfo = XS_KCplayVideohourInfoM() // 课时信息
    var hourList: [XS_KCplayVideohourListM] = [] // 同章节课时列表
}

class XS_KCDetailVC: XS_BaseVC {
    weak var player: XS_KCVideo?
    deinit {
        player?.player?.destroy()
    }
    
    var curriculum: XS_KCcurriculumM!
    lazy var collectionPS = PublishSubject<Bool>()
    lazy var id = 0
    var model: XS_KCplayVideoM!
    lazy var dataPS = PublishSubject<XS_KCplayVideoM>()
    lazy var ss = getScroll()
    
    func onAction(_ type: XS_KCBaseVC.ActionType) {
        guard let curriculum = curriculum else { return }
        switch type {
        case .分享:
            guard let url = URL(string: "/course?id=\(curriculum.id)".spliceH5Api()) else { return }
            let activityVc = UIActivityViewController(activityItems: [url], applicationActivities: nil)
            XS_NVC.shared.present(activityVc, animated: true)
        case .想学:
            if curriculum.isCollect == "yes" {
                curriculum.isCollect = "no"
                _ = XS_NetWork.requestJson("/collection/collectionCancel", parameters: ["relation":curriculum.id,"type":"curriculum"])
                    .subscribe()
            } else {
                curriculum.isCollect = "yes"
                _ = XS_NetWork.requestJson("/collection/collectionButton", parameters: ["relation":curriculum.id,"type":"curriculum"])
                    .subscribe()
            }
            collectionPS.onNext(curriculum.isCollect == "yes")
        default: break
        }
    }
    
    override func upConfig() {
        shouldNavBarHidden = true
        isStatusBarBlack = false
    }
    override func upView() {
        Observable<Int>.interval(.seconds(60), scheduler: MainScheduler.asyncInstance)
            .subscribe(onNext: { _ in
                guard XS_Singleton.shared.infoModel != nil else { return }
                _ = XS_NetWork.requestJson("/plan/uploadUserLearnTime", parameters: ["time": "1"])
                    .subscribe()
            }).disposed(by: disposeBag)
        
        view.addSubview(ss)
        let top = UIView()
        top.alpha = 0
        top.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
        view.addSubview(top)
        loadCustomBar()
        
        top.snp.makeConstraints({
            $0.left.right.top.equalToSuperview()
            $0.bottom.equalTo(customBar.snp.bottom)
        })
        ss.snp.makeConstraints({
            $0.left.right.top.bottom.equalToSuperview()
        })
        
        ss.rx.contentOffset
            .subscribe(onNext: { offset in
                top.alpha = offset.y / (.scale*240 - 44 - .barHeight)
            }).disposed(by: disposeBag)
        
        let share = QMUIButton()
        share.setBackgroundImage(UIImage(named: "icon_分享备份"), for: .normal)
        view.addSubview(share)
        share.snp.makeConstraints({
            $0.width.height.equalTo(24)
            $0.centerY.equalTo(customBar.snp.centerY)
            $0.right.equalTo(-16)
        })
        share.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.onAction(.分享)
            }).disposed(by: disposeBag)
        
        
//        let xiangxue = QMUIButton()
//        xiangxue.setBackgroundImage(UIImage(named: "icon_24px_收藏_1"), for: .normal)
//        xiangxue.setBackgroundImage(UIImage(named: "icon_64_收藏_绿_1"), for: .selected)
//        view.addSubview(xiangxue)
//        xiangxue.snp.makeConstraints({
//            $0.width.height.equalTo(24)
//            $0.centerY.equalTo(customBar.snp.centerY)
//            $0.right.equalTo(-56)
//        })
//        xiangxue.rx.tap.asDriver()
//            .drive(onNext: { [weak self] in
//                self?.onAction(.想学)
//            }).disposed(by: disposeBag)
//
        let video = XS_KCVideo()
        player = video
        ss.addSubview(video)
        video.snp.makeConstraints({
            $0.top.left.width.equalToSuperview()
            $0.height.equalTo(.scale*240)
        })
        collectionPS.startWith(curriculum.isCollect == "yes")
            .subscribe(onNext: { set in
//                xiangxue.isSelected = set
                video.collectionPS.onNext(set)
            }).disposed(by: disposeBag)
        video.actionPS.subscribe(onNext: { [weak self] type in
            self?.onAction(type)
        }).disposed(by: disposeBag)
        
        let titleView = XS_KCTitle()
        ss.addSubview(titleView)
        titleView.snp.makeConstraints({
            $0.left.width.equalToSuperview()
            $0.top.equalTo(video.snp.bottom)
        })
        
        let hour = XS_KCHour()
        hour.actionPS
            .subscribe(onNext: { [weak self] model in
                self?.reload("\(model.id)")
            }).disposed(by: disposeBag)
        ss.addSubview(hour)
        hour.snp.makeConstraints({
            $0.left.width.equalToSuperview()
            $0.top.equalTo(titleView.snp.bottom)
        })
        
        let line = UIView()
        line.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        ss.addSubview(line)
        line.snp.makeConstraints({
            $0.left.width.equalToSuperview()
            $0.height.equalTo(.scale*8)
            $0.top.equalTo(hour.snp.bottom)
        })
        
        let biaoqian = XS_KCBiaoqian(["介绍", "快学"]) { [weak self] index in
            guard let `self` = self else { return nil }
            switch index {
            case 0: return self.getJieshao()
            case 1: return self.getFaxian()
            default: return nil
            }
        }
        ss.addSubview(biaoqian)
        biaoqian.snp.makeConstraints({
            $0.top.equalTo(line.snp.bottom)
            $0.left.width.equalToSuperview()
            $0.bottom.lessThanOrEqualToSuperview()
        })
        
        dataPS.startWith(model)
            .subscribe(onNext: { item in
                video.imgPS.onNext(item.hourInfo.imgUrl)
                video.modelPS.onNext(item.sts)
                titleView.modelPS.onNext((item.hourInfo.curriculumHourTitle, item.hourInfo.label.components(separatedBy: ",")))
                hour.isBuy = item.isBuy
                hour.modelPS.onNext(item.hourList)
            }).disposed(by: disposeBag)
    }
    
    private lazy var needLoad = false
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if needLoad {
            reload(model.hourInfo.curriculumId)
            needLoad = false
        }
    }
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        player?.player?.pause()
    }
    
    func reload(_ id: String) {
        XS_NetWork.requestJson("/file/playVideo", parameters: ["id":id])
            .mapModel(type: XS_KCplayVideoM.self)
            .subscribe(onNext: { [weak self] model, resp in
                guard let `self` = self else { return }
                if resp.code == "00403" { // 购买
                    guard XS_Singleton.shared.infoModel != nil else {
                        XS_NVC.shared.toLogin(false)
                        return
                    }
//                    self.needLoad = true
//                    let buyVC = XS_BuyVC()
//                    buyVC.courseId = "\(self.curriculum.id)"
//                    buyVC.courseClassification = "online"
//                    XS_NVC.shared.pushViewController(buyVC, animated: true)
                    self.view.makeToast("请购买或领取后观看")
                    return
                }
                guard resp.success, let model = model else { return }
                self.model = model
                self.dataPS.onNext(model)
            }).disposed(by: disposeBag)
    }
    
    private func getScroll() -> UIScrollView {
        let scroll = UIScrollView()
        scroll.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        scroll.bounces = false
        scroll.contentInsetAdjustmentBehavior = .never
        scroll.showsVerticalScrollIndicator = false
        return scroll
    }
    func getJieshao() -> UIView {
        let view = UIView()
        
        let bg = UIView()
        bg.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        view.addSubview(bg)
        bg.snp.makeConstraints({
            $0.left.top.right.equalToSuperview()
            $0.bottom.lessThanOrEqualToSuperview().offset(-.scale*16 - .bottomHeight)
        })
        let imgV = UIImageView()
        bg.addSubview(imgV)
        imgV.snp.makeConstraints({
            $0.left.top.equalTo(.scale*16)
            $0.right.bottom.equalTo(-.scale*16)
            $0.height.equalTo(1)
        })
        
        imgV.sd_setImage(with: URL(string: curriculum.descriptionImgUrl)) { img, _, _, _ in
            imgV.snp.remakeConstraints({
                $0.left.top.equalTo(.scale*16)
                $0.right.bottom.equalTo(-.scale*16)
                if let size = img?.size, size.width > 0 {
                    $0.height.equalTo(imgV.snp.width).multipliedBy(size.height/size.width)
                }
            })
        }
        
        return view
    }
    func getFaxian() -> UIView {
        let view = UIView()
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: .scale*166, height: .scale*281)
        flowLayout.minimumLineSpacing = .scale*16
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.sectionInset = UIEdgeInsets(top: .scale*16, left: .scale*16, bottom: .scale*16, right: .scale*16)
        let collection = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collection.showsVerticalScrollIndicator = false
        collection.showsHorizontalScrollIndicator = false
        collection.bounces = false
        collection.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        view.addSubview(collection)
        var constraint: Constraint!
        collection.snp.makeConstraints {
            $0.left.top.right.equalToSuperview()
            constraint = $0.height.equalTo(.scale*32).constraint
            $0.bottom.lessThanOrEqualTo(-.scale*32 - .bottomHeight)
        }
        collection.rx.observe(CGSize.self, "contentSize")
            .subscribe(onNext: { size in
                guard let size = size, size != .zero else { return }
                constraint.update(offset: size.height)
            }).disposed(by: self.disposeBag)
        collection.register(XS_FaxianCell.self, forCellWithReuseIdentifier: "cell")
        let dataSource = RxCollectionViewSectionedReloadDataSource<SectionModel<String, XS_discoverQuickLearnM>>(configureCell: { ds, cv, ip, it in
            let cell = cv.dequeueReusableCell(withReuseIdentifier: "cell", for: ip) as! XS_FaxianCell
            cell.layer.corner(radius: .scale*4, bgColor: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), isShadow: true, sColor: #colorLiteral(red: 0.1843137255, green: 0.2039215686, blue: 0.2039215686, alpha: 1), offset: CGSize(width: 0, height: .scale*2), effect: .scale*12, opacity: 0.06)
            cell.layer.masksToBounds = false
            cell.modelPS.onNext(it)
            return cell
        })
        
        let param: [String:Any] = [
            "pageNum":1,
            "pageSize":"100",
            "industryId":curriculum.industryId
        ]
        
        XS_NetWork.requestJson("/quick/discoverQuickLearn", parameters: param)
            .mapModel(type: XS_ListM<XS_discoverQuickLearnM>.self)
            .compactMap { $0.0?.records }
            .asDriver(onErrorJustReturn: [])
            .flatMapLatest { Driver.just([SectionModel<String, XS_discoverQuickLearnM>(model: "", items: $0)]) }
            .drive(collection.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
        
        collection.rx.modelSelected(XS_discoverQuickLearnM.self)
            .asDriver()
            .drive(onNext: { item in
                let vc = XS_KuaiXueDetailVC()
                vc.id = item.id
                XS_NVC.shared.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        return view
    }
}
